<template>
  <div class="unit-center">
    <el-card class="box-card">
      <!-- 头部操作区 -->
      <div class="header-actions">
        <el-button type="primary" @click="openAddDialog" size="small">
          <el-icon><Plus /></el-icon>新增教学单元
        </el-button>
      </div>

      <!-- 表格区域 -->
      <el-table
          :data="units"
          style="width: 100%"
          border
          @selection-change="handleSelectionChange"
          :header-cell-style="{ background: '#f5f7fa' }"
      >
        <el-table-column type="selection" width="55" align="center"></el-table-column>
        <el-table-column prop="unitTitle" label="单元名称" min-width="200"></el-table-column>
        <el-table-column prop="courseName" label="关联课程" min-width="200"></el-table-column>
        <el-table-column prop="status" label="状态" width="100" align="center">
          <template #default="scope">
            <el-tag :type="statusType(scope.row.status)" effect="light">
              {{ getStatusText(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="280" align="center" fixed="right">
          <template #default="scope">
            <el-button type="primary" size="small" plain @click="editUnit(scope.row)">
              <el-icon><Edit /></el-icon>编辑
            </el-button>
            <el-button type="danger" size="small" plain @click="deleteUnit(scope.row.id)">
              <el-icon><Delete /></el-icon>删除
            </el-button>
            <el-button type="info" size="small" plain @click="showProgress(scope.row)">
              <el-icon><DataAnalysis /></el-icon>完成情况
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页区域 -->
      <div class="pagination-container">
        <el-pagination
            background
            layout="total, prev, pager, next"
            :current-page="pagination.currentPage"
            :page-size="pagination.pageSize"
            :total="pagination.total"
            @current-change="handlePageChange">
        </el-pagination>
      </div>
    </el-card>

    <!-- 添加/编辑对话框 -->
    <el-dialog
        v-model="dialogVisible"
        :title="form.id ? '编辑教学单元' : '新增教学单元'"
        width="50%"
        destroy-on-close
    >
      <el-form
          :model="form"
          :rules="rules"
          ref="form"
          label-width="120px"
          class="dialog-form"
      >
        <el-form-item label="单元名称" prop="unitTitle">
          <el-input v-model="form.unitTitle" placeholder="请输入单元名称"></el-input>
        </el-form-item>

        <!-- 文档上传 -->
        <el-form-item label="教学文档" prop="docFile">
          <el-upload
              class="upload-demo"
              :action="getUploadUrl('document')"
              :headers="headers"
              :on-success="handleDocSuccess"
              :on-error="handleUploadError"
              :before-upload="beforeDocUpload"
              :file-list="docFileList">
            <el-button type="primary">选择文档</el-button>
            <template #tip>
              <div class="el-upload__tip">
                支持 doc, docx, pdf 格式文件，大小不超过20MB
              </div>
            </template>
          </el-upload>
        </el-form-item>

        <!-- 视频上传 -->
        <el-form-item label="教学视频" prop="videoFile">
          <el-upload
              class="upload-demo"
              :action="getUploadUrl('video')"
              :headers="headers"
              :on-success="handleVideoSuccess"
              :on-error="handleUploadError"
              :before-upload="beforeVideoUpload"
              :file-list="videoFileList">
            <el-button type="primary">选择视频</el-button>
            <template #tip>
              <div class="el-upload__tip">
                支持 mp4, avi 格式视频文件，大小不超过500MB
              </div>
            </template>
          </el-upload>
        </el-form-item>

        <el-form-item label="单元介绍" prop="unitIntroduce">
          <el-input
              type="textarea"
              v-model="form.unitIntroduce"
              rows="4"
              placeholder="请输入单元介绍"
          ></el-input>
        </el-form-item>
        <el-form-item label="是否为章单元" prop="isChpt">
          <el-select v-model="form.isChpt" placeholder="请选择">
            <el-option label="章单元" value="1"></el-option>
            <el-option label="小节单元" value="0"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="关联课程" prop="courseId">
          <el-select v-model="form.courseId" placeholder="请选择课程">
            <el-option
                v-for="course in courseList"
                :key="course.id"
                :label="course.courseName"
                :value="course.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="发布状态" prop="status">
          <el-select v-model="form.status" placeholder="请选择状态">
            <el-option label="未发布" value="0"></el-option>
            <el-option label="已发布" value="1"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="handleSave">确 定</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 完成情况对话框 -->
    <el-dialog
        v-model="progressDialogVisible"
        title="单元完成情况"
        width="70%"
        destroy-on-close>
      <div class="progress-container">
        <!-- 饼图区域 -->
        <div class="chart-area">
          <div ref="pieChart" style="width: 100%; height: 300px;"></div>
        </div>

        <!-- 完成情况表格 -->
        <div class="progress-table">
          <el-table :data="studentProgress" border style="width: 100%">
            <el-table-column prop="studentName" label="学生姓名" width="120"></el-table-column>
            <el-table-column prop="finishedStatus" label="完成状态" width="100">
              <template #default="scope">
                <el-tag :type="scope.row.finishedStatus === '1' ? 'success' : 'warning'">
                  {{ scope.row.finishedStatus === '1' ? '已完成' : '未完成' }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="finishedTime" label="完成时间" min-width="180">
              <template #default="scope">
                {{ scope.row.finishedStatus === '1' ? formatDateTime(scope.row.finishedTime) : '-' }}
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
    </el-dialog>
  </div>
</template>



<script>
import * as echarts from 'echarts';

export default {
  name: "UnitCenter",
  data() {
    return {
      uploadUrl: 'http://localhost:8081/file/upload', // 文件上传地址
      headers: {
        Authorization: localStorage.getItem("token")
      },
      docFileList: [],
      videoFileList: [],


      units: [],  // 存储教学单元列表
      selectedUnits: [],
      pagination: {
        currentPage: 1,
        pageSize: 5,
        total: 0
      },
      dialogVisible: false,
      progressDialogVisible: false, // 完成情况对话框
      studentProgress: [], // 学生完成情况数据
      pieChart: null, // echarts实例
      initialForm: {
        id: null,
        unitTitle: '',
        docPath: '',
        videoPath: '',
        unitIntroduce: '',
        fatherId: null,
        isChpt: '0',
        courseId: null,
        status: '0',
        docFileName: '', // 新增：文档原始文件名
        videoFileName: '' // 新增：视频原始文件名
      },
      form: {}, // form 将在需要时被赋值
      courseList: [], // 用于存储所有课程
      rules: {
        unit_title: [{ required: true, message: '请输入单元名称', trigger: 'blur' }],
        status: [{ required: true, message: '请选择发布状态', trigger: 'change' }],
      }
    };
  },
  created() {
    this.fetchUnits();
    this.fetchCourses();
  },
  methods: {
    getUploadUrl(fileType) {
      const unitId = this.form.id || 'new';
      return `http://localhost:8081/file/upload/${unitId}?fileType=${fileType}`;
    },

    // 处理文档上传成功
    handleDocSuccess(response, file) {
      if (response.code === 200) {
        this.form.docPath = response.data.filePath;
        this.form.docFileName = file.name;
        ElMessage.success('文档上传成功');
      } else {
        ElMessage.error('文档上传失败');
      }
    },

    // 处理视频上传成功
    handleVideoSuccess(response, file) {
      if (response.code === 200) {
        this.form.videoPath = response.data.filePath;
        this.form.videoFileName = file.name;
        ElMessage.success('视频上传成功');
      } else {
        ElMessage.error('视频上传失败');
      }
    },

    // 上传失败处理
    handleUploadError() {
      ElMessage.error('上传失败，请重试');
    },

    // 文档上传前的验证
    beforeDocUpload(file) {
      const validTypes = ['application/pdf', 'application/msword', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'];
      const isValidType = validTypes.includes(file.type);
      const isLt20M = file.size / 1024 / 1024 < 20;

      if (!isValidType) {
        ElMessage.error('只能上传PDF/Word文档!');
        return false;
      }
      if (!isLt20M) {
        ElMessage.error('文件大小不能超过20MB!');
        return false;
      }
      return true;
    },

    // 视频上传前的验证
    beforeVideoUpload(file) {
      const isValidType = file.type.includes('video/');
      const isLt500M = file.size / 1024 / 1024 < 500;

      if (!isValidType) {
        ElMessage.error('只能上传视频文件!');
        return false;
      }
      if (!isLt500M) {
        ElMessage.error('视频大小不能超过500MB!');
        return false;
      }
      return true;
    },

    // 显示进度情况
    async showProgress(unit) {
      this.progressDialogVisible = true;
      this.currentUnit = unit;

      try {
        const response = await this.$axios.get(`/teaching-student-learning/progress/${unit.id}`, {
          headers: { Authorization: localStorage.getItem("token") }
        });

        this.studentProgress = response.data.data;
        this.$nextTick(() => {
          this.initPieChart();
        });
      } catch (error) {
        console.error('获取进度数据失败:', error);
        ElMessage.error('获取进度数据失败');
      }
    },

    // 原有方法保持不变
    fetchUnits() {
      const teacherId = this.$store.getters.getUser.id;

      this.$axios.get('/course-learn-unit/units', {
        params: {
          currentPage: this.pagination.currentPage,
          teacherId: teacherId
        },
        headers: { Authorization: localStorage.getItem("token") }
      }).then(async response => {
        console.log(response.data.data);
        const data = response.data.data;
        const units = data.records;

        for (const unit of units) {
          if (unit.courseId) {
            try {
              const courseResponse = await this.$axios.get(`/course/course/${unit.courseId}`, {
                headers: { Authorization: localStorage.getItem("token") }
              });
              if (courseResponse.data.data.teacherId === teacherId) {
                unit.courseName = courseResponse.data.data.courseName;
              }
            } catch (error) {
              console.error(`Error fetching courseName for courseId ${unit.courseId}:`, error);
              unit.courseName = "未知课程";
            }
          } else {
            unit.courseName = "未关联课程";
          }
        }

        this.units = units.filter(unit => unit.courseName !== "未知课程" && unit.courseName !== "未关联课程");
        this.pagination.total = this.units.length;
      }).catch(error => {
        console.error('Error fetching units:', error);
        ElMessage.error('获取单元列表失败');
      });
    },

    fetchCourses() {
      const teacherId = this.$store.getters.getUser.id;

      this.$axios.get('/course/courses', {
        params: {
          currentPage: this.pagination.currentPage,
          teacherId: teacherId
        },
        headers: {
          Authorization: localStorage.getItem("token")
        }
      }).then((res) => {
        this.courseList = res.data.data.records;
      }).catch((error) => {
        console.error('Error fetching courses:', error);
        this.$message.error('获取课程列表失败');
      });
    },

    // 新增的方法
    async showProgress(unit) {
      this.progressDialogVisible = true;
      await this.fetchStudentProgress(unit.id);
      this.$nextTick(() => {
        this.initPieChart();
      });
    },

    async fetchStudentProgress(unitId) {
      try {
        const response = await this.$axios.get(`/teaching-student-learning/progress/${unitId}`, {
          headers: { Authorization: localStorage.getItem("token") }
        });
        this.studentProgress = response.data.data;
      } catch (error) {
        console.error('Error fetching student progress:', error);
        ElMessage.error('获取完成情况失败');
      }
    },

    initPieChart() {
      if (this.pieChart) {
        this.pieChart.dispose();
      }

      const completed = this.studentProgress.filter(s => s.finishedStatus === '1').length;
      const total = this.studentProgress.length;
      const uncompleted = total - completed;

      this.pieChart = echarts.init(this.$refs.pieChart);
      const option = {
        title: {
          text: '单元完成情况统计',
          left: 'center'
        },
        tooltip: {
          trigger: 'item',
          formatter: '{b}: {c} ({d}%)'
        },
        legend: {
          orient: 'vertical',
          left: 'left'
        },
        series: [
          {
            type: 'pie',
            radius: '50%',
            data: [
              { value: completed, name: '已完成', itemStyle: { color: '#67C23A' } },
              { value: uncompleted, name: '未完成', itemStyle: { color: '#E6A23C' } }
            ],
            emphasis: {
              itemStyle: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: 'rgba(0, 0, 0, 0.5)'
              }
            }
          }
        ]
      };
      this.pieChart.setOption(option);
    },

    formatDateTime(date) {
      if (!date) return '-';
      return new Date(date).toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit'
      });
    },

    // 保持原有的其他方法不变
    handlePageChange(page) {
      this.pagination.currentPage = page;
      this.fetchUnits();
    },
    handleSelectionChange(selectedRows) {
      this.selectedUnits = selectedRows;
    },
    editUnit(unit) {
      this.dialogVisible = true;
      this.form = { ...unit };
    },
    openAddDialog() {
      this.dialogVisible = true;
      this.form = { ...this.initialForm };
    },
    handleSave() {
      const unitData = {
        id: this.form.id,
        unitTitle: this.form.unitTitle,
        docPath: this.form.docPath,
        videoPath: this.form.videoPath,
        unitIntroduce: this.form.unitIntroduce,
        isChpt: this.form.isChpt,
        courseId: this.form.courseId,
        status: this.form.status
      };
      const apiUrl = '/course-learn-unit/saveOrUpdate';

      this.$axios.post(apiUrl, unitData, {
        headers: { Authorization: localStorage.getItem("token") }
      }).then(response => {
        ElMessage.success('操作成功');
        this.fetchUnits();
        this.dialogVisible = false;
      }).catch(error => {
        ElMessage.error('操作失败');
      });
    },
    deleteUnit(id) {
      ElMessageBox.confirm('确定删除该教学单元吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$axios.delete(`/course-learn-unit/delete/${id}`, {
          headers: { Authorization: localStorage.getItem("token") }
        }).then(() => {
          ElMessage.success('删除成功');
          this.fetchUnits();
        }).catch(error => {
          ElMessage.error('删除失败');
        });
      });
    },
    getStatusText(status) {
      return status === "1" ? '已发布' : '未发布';
    },
    statusColor(status) {
      return status === true ? 'green' : 'gray';
    },
    statusType(status) {
      return status === "1" ? 'success' : 'danger';
    }
  }
};
</script>

<style scoped>
.unit-center {
  padding: 20px;
}

.header-actions {
  margin-bottom: 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.box-card {
  margin-bottom: 20px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
  padding: 10px 0;
}

.dialog-form {
  padding: 20px 20px 0 20px;
}

.dialog-footer {
  text-align: right;
  padding: 20px;
}

.progress-container {
  padding: 20px;
}

.chart-area {
  margin-bottom: 20px;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  padding: 20px;
}

.progress-table {
  margin-top: 20px;
}

:deep(.el-table) {
  margin: 15px 0;
}

:deep(.el-button) {
  margin: 0 5px;
}

:deep(.el-form-item) {
  margin-bottom: 22px;
}

:deep(.el-input),
:deep(.el-select) {
  width: 100%;
}

:deep(.el-dialog__body) {
  padding: 0;
}
</style>